<template>
 <el-dialog 
     :title="nameTitle" 
     :visible.sync="dialogVisible" 
     width="58%" 
     :fullscreen="isFullscreen"
     class="drug-info-dialog"
     @close="handleClose"
	 :modal="false"
	 :show-close="false"
	 :close-on-click-modal="false"
     @contextmenu.native.prevent="showContextMenu">
     
     <!-- 在el-dialog的header部分添加自定义内容 -->
     <template slot="title">
       <div class="dialog-header">
         <span>{{ nameTitle }}</span>
         <div class="header-buttons">
           <el-button 
             type="text" 
             size="medium" 
             @click="toggleFullscreen"
             :icon="isFullscreen ? 'el-icon-minimize' : 'el-icon-full-screen'"
             :title="isFullscreen ? '退出全屏' : '全屏显示'">
           </el-button>
           <el-button 
             type="text" 
             size="medium" 
             @click="dialogVisible = false" 
             icon="el-icon-close"
             title="关闭">
           </el-button>
         </div>
       </div>
     </template>
    <!-- 使用Cascader作为右键菜单 -->
    <el-cascader-panel
        v-if="contextMenuVisible"
        v-model="cascaderValue"
        :options="contextMenuOptions"
        :props="{ expandTrigger: 'hover' }"
        :style="{
        position: 'fixed',
        left: contextMenuX + 'px',
        top: contextMenuY + 'px',
        zIndex: 999,
        border: '1px solid #e0e0e0',
        borderRadius: '4px',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
      }"
        @change="handleMenuSelect"
        @blur="hideContextMenu"
        ref="cascaderMenu">
    </el-cascader-panel>
    <!-- 顶部表单区域 (top) -->
    <div class="form-top">
      <el-form :model="form" ref="topForm" label-width="88px" size="mini" :rules="addRules" :disabled="formDisabled || mode === 'view'">
        <!-- 第一行：药典名称和详细按钮 -->
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="药典名称：" prop="drugCodeId" >
              <!-- selectName -->
              <el-select 
                v-model="form.drugCodeId" 
                filterable
                remote
                :remote-method="searchNameMethod"
                @focus="handlefoucsName" 
                @change="handleNameChange" 
                :popper-append-to-body="false"
                :loading="loading"
              >
              <!-- 选项组 -->
              <el-group>
                <!-- 固定头部 -->
                <div class="select-header" slot="header" 
                style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-between;padding: 8px;
                position: sticky;top:0;z-index: 10;background-color: #f1f1f1;">
                  <span style="width: 48px;">药品序号</span>
                  <span>药品名称</span>
                  <span>规格</span>
                  <span>药品编码</span>
                  <span>剂型</span>
                  <span>厂家</span>
                </div>
                <el-option 
                  v-for="item in NameOptions" 
                  :key="item._uid" 
                  :label="item.label" 
                  :value="item.id"
                >
                  <div id="optionItem">
                    <span style="width: 48px;">{{ item.id }}</span>
                    <span>{{ item.label }}</span>
                    <el-tooltip class="item" effect="light" :content="item.specifications" placement="top">
                      <span>{{ item.specifications }}</span>
                    </el-tooltip>
                    <span>{{ item.drugCode }}</span>
                    <span>{{ item.dosageForm }}</span>
                    <span>{{ item.licensorChinese }}</span>
                  </div>
                </el-option>
                </el-group>
                <!-- 加载状态提示 -->
                <div v-if="loading" slot="empty" class="load-more">
                  <i class="el-icon-loading"></i> 加载中...
                </div>
                <div v-else-if="scrollLoading" slot="empty" class="load-more">
                  <i class="el-icon-loading"></i> 加载更多...
                </div>
                <div v-else-if="!hasMore && NameOptions.length > 0" slot="empty" class="load-more">
                  没有更多数据了
                </div>
                <div v-else-if="NameOptions.length === 0" slot="empty" class="load-more">
                  暂无数据
                </div>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item style="margin-left: -88px;">
              <el-button type="success" size="mini" @click="copyDrugName" icon="el-icon-document-copy">复制</el-button>
              <el-button type="primary" size="mini" @click="showDetails">详细[2]</el-button>
			  <!-- 新增更新加成率按钮 -->
			  <el-button 
			    v-if="form.markUpId === 1"
			    type="warning" 
			    size="mini" 
			    @click="updateMarkUpRate"
			    icon="el-icon-refresh">
			    更新
			  </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第二行：药品剂型、药品类型、抗生素否、皮试否 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="药品剂型：">
              <el-input v-model="this.form.dosageForm" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品类型：">
              <!-- 单位 -->
              <el-select v-model="this.form.drugType" style="margin-left: 4px;" disabled placeholder=''>
                <el-option v-for="item in drugTypeOption" :key="item.id" :label="item.label" :value="item.id">
                  <span>{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
	<!-- 	  <el-col :span="6">
		      <el-form-item label="处方类型：">
		        <el-select 
		          v-model="form.rxType" 
		          style="margin-left: 4px;" 
		          placeholder='请选择处方类型'
		        >
		          <div class="bbox" style="padding: 8px;">
					  <el-option
					  style="border: 2px solid #c6c6c6;border-radius: 8px;"
					    v-for="item in rxTypeoptions" 
					    :key="item.id" 
					    :label="item.label" 
					    :value="item.id"
					    :style="item.style"
					  >
					    <span :style="item.style" style="font-size: 12px;">{{ item.label }}</span>
					  </el-option>
				  </div>
		        </el-select>
		      </el-form-item>
		    </el-col> -->
			<el-col :span="3">
			  <el-form-item label="有效状态">
				<el-checkbox 
				  v-model="form.state" 
				  :true-label="1"
				  :false-label="0"
				  @change="handleCheckboxChangeState">
				  <!-- {{ form.state === 1 ? '启用' : '禁用' }} -->
				</el-checkbox>
			  </el-form-item>
			</el-col>
			<el-col :span="3">
                <el-form-item label="抗生素否">
                  <el-checkbox 
                    v-model="form.antc" 
                    :true-label="1" 
                    :false-label="0"
                    @change="handleCheckboxChange('antc')">
                  </el-checkbox>
                </el-form-item>
			</el-col>
			<el-col :span="3">
			<el-form-item label="皮试否：">
			  <el-checkbox 
				v-model="form.skintstDicm" 
				:true-label="1" 
				:false-label="0"
				@change="handleCheckboxChange('skintstDicm')">
			  </el-checkbox>
			</el-form-item>
		  </el-col>
        </el-row>
      </el-form>
    </div>
    
    <!-- 中间标签页区域 (main) -->
    <div class="form-main">
      <el-tabs type="border-card" v-model="activeTab">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本内容[F2]" name="basic">
          <div class="tab-content">
            <basic-info 
              ref="basicInfo"
              :form="form" 
              :form-disabled="formDisabled || mode === 'view'"
              :mode="mode"
              @update="handleFormUpdate">
            </basic-info>
          </div>
        </el-tab-pane>
        
        <!-- 扩展信息标签页 -->
        <el-tab-pane label="扩展信息[F3]" name="extended">
          <div class="tab-content">
            <kz-info 
              ref="kzInfo"
              :form="form" 
              :form-disabled="formDisabled || mode === 'view'"
              :mode="mode"
              @update="handleFormUpdateF3">
            </kz-info>
          </div>
        </el-tab-pane>
        
        <!-- 使用注意标签页 -->
        <el-tab-pane label="使用注意[F4]" name="usage">
          <div class="tab-content">
            <use-info 
              ref="useInfo"
              :form="form" 
              :form-disabled="formDisabled || mode === 'view'"
              :mode="mode"
              @update="handleFormUpdateF4">
            </use-info>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 底部表格区域 (feet) -->
    <div class="form-feet">
      <div class="CJ">
        <!-- 修改厂家标题按钮区域 -->
        <div class="CJ-title">
          <span class="title-text">厂家信息</span>
          <div class="title-buttons" v-if="mode !== 'view'">
            <el-button type="text" icon="el-icon-plus" @click="addManufacturer"></el-button>
            <el-button type="text" icon="el-icon-edit" @click="editManufacturer" :disabled="!currentManufacturer"></el-button>
            <el-button type="text" icon="el-icon-delete" @click="deleteManufacturer" :disabled="!currentManufacturer"></el-button>
          </div>
          <div class="title-buttons" v-else>
            <el-button type="text" icon="el-icon-plus" disabled></el-button>
            <el-button type="text" icon="el-icon-edit" disabled></el-button>
            <el-button type="text" icon="el-icon-delete" disabled></el-button>
          </div>
        </div>
        <div class="CJ-table">
			<!-- height="100%" -->
          <el-table
            :data="manufacturerData"
			highlight-current-row
            border
            style="width: 100%"
            @current-change="handleManufacturerSelect">
            <el-table-column
              type="index"
              label="行号"
              width="50"
              align="center">
            </el-table-column>
			<el-table-column prop="status" label="有效状态" width="120" sortable>
				<template slot-scope="{ row }">
					<span style="color: #00557f;font-weight: bold;">{{ statusMap[row.status] }}</span>
				</template>
			</el-table-column>
            <el-table-column
              prop="manufacturerName"
              label="生产厂家"
              width="180">
            </el-table-column>
            <el-table-column
              prop="expyDate"
              label="有效期天数"
              width="120">
            </el-table-column>
			
            <el-table-column
              prop="orplc"
              label="产地"
              width="120">
            </el-table-column>

			<el-table-column prop="drugTracB" label="是否已开启强制追溯码" width="168" sortable>
				<template slot-scope="{ row }">
					<span style="color: brown;font-weight: bold;">{{ drugTracBMap[row.drugTracB] }}</span>
				</template>
			</el-table-column>
			
			<el-table-column
			  prop="drugTracMaxId"
			  label="大包装追溯标识码"
			  width="120">
			</el-table-column>
			<el-table-column
			  prop="drugTracMinId"
			  label="小包装追溯标识码"
			  width="120">
			</el-table-column>
			<el-table-column
			  prop="drugTracMaxCnt"
			  label="大包装追溯码换算数量"
			  width="148">
			</el-table-column>
            <el-table-column
              prop="ratio"
              label="自付比例"
              width="120">
            </el-table-column>
            <el-table-column
              prop="bidCnt"
              label="中标次数"
              width="99">
            </el-table-column>
            <el-table-column
              prop="manuLotnum"
              label="生产批号"
              width="120">
            </el-table-column>
            <el-table-column
              prop="netCode"
              label="网采编码"
              width="100">
            </el-table-column>
			<el-table-column
			  prop="chsName"
			  label="医保名称"
			  width="100">
			</el-table-column>
			<el-table-column
			  prop="chsCode"
			  label="医保编码"
			  width="100">
			</el-table-column>
			<el-table-column
			  prop="ypId"
			  label="ypId"
			  width="120">
			</el-table-column>
			<el-table-column
			  prop="regModel"
			  label="注册型号"
			  width="100">
			</el-table-column>
			<el-table-column
			  prop="regSpc"
			  label="注册规格"
			  width="100">
			</el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    
    <!-- 修改底部按钮区域 -->
    <div slot="footer" class="dialog-footer" v-if="mode !== 'view'">
      <el-button size="mini" type="primary" @click="submitForm">
        {{ mode === 'add' ? '确定' : '保存' }}
      </el-button>
      <el-button size="mini" @click="dialogVisible = false">关闭</el-button>
    </div>
    <div slot="footer" class="dialog-footer" v-else>
      <el-button size="mini" @click="dialogVisible = false">关闭</el-button>
    </div>
	
    <!-- 药典详情弹窗 -->
    <el-dialog
      title="查看【西药】药典详情"
      :visible.sync="seeDetailsVisible"
      width="40%"
      :append-to-body="true"
      :before-close="handleCloseDetails">
      <el-descriptions :title="drugData.label" direction="vertical" :column="5" border>
        <el-descriptions-item label="药品序号">{{ drugData.id }}</el-descriptions-item>
        <el-descriptions-item label="药品编码">{{ drugData.drugCode }}</el-descriptions-item>
        <el-descriptions-item label="药品剂型">{{ drugData.dosageForm }}</el-descriptions-item>
        <el-descriptions-item label="批准文号">{{ drugData.approvalNumber }}</el-descriptions-item>
        <el-descriptions-item label="生产厂家">
          <el-tag size="small">{{ drugData.licensorChinese }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="规格描述">{{ drugData.specifications }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="seeDetailsVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 厂家信息弹窗 -->
    <el-dialog
      title="厂家信息"
      :visible.sync="manufacturerDialogVisible"
      width="40%"
	  :modal="false"
	  :show-close="false"
      :before-close="handleCloseManufacturerDialog">
	  <!-- 在el-dialog的header部分添加自定义内容 -->
	  <template slot="title">
	    <div class="dialog-header">
	      <span>厂家信息</span>
	      <div class="header-buttons">
	        <el-button 
	          type="text" 
	          size="medium" 
	          @click="manufacturerDialogVisible = false" 
	          icon="el-icon-close"
	          title="关闭">
	        </el-button>
	      </div>
	    </div>
	  </template>
      <el-form :model="manufacturerForm" :rules="prodentrules" ref="manufacturerForm" label-width="168px" size="mini" style="font-size: 12px;">
        <el-row :gutter="20">
          <el-col :span="12">
			<el-form-item label="生产厂家" prop="prodentpId">
			  <el-select 
			    v-model="manufacturerForm.prodentpId" 
			    filterable
			    remote
			    :remote-method="CJsearchNameMethod"
			    @focus="handlefoucsNameCJ" 
			    @change="handleNameChangeCJ" 
			    :popper-append-to-body="false"
			    :loading="loading"
			    style="width: 100%"
			  >
			  
			    <!-- 选项组 -->
			    <el-group>
			      <!-- 固定头部 - 修改为使用固定列宽 -->
			      <div class="select-header" slot="header" 
			        style="
			          font-size: 12px;
			          font-weight: bold;
			          display: flex;
			          padding: 8px;
			          position: sticky;
			          top:0;
			          z-index: 10;
			          background-color: #f1f1f1;
			          width: 100%;
			        ">
			        <span style="width: 60px; flex-shrink: 0; text-align: center;">厂家序号</span>
			        <span style="width: 220px; flex-shrink: 0; text-align: center;">厂家名称</span>
			        <span style="width: 100px; flex-shrink: 0; text-align: center;">厂家编码</span>
			        <span style="width: 60px; text-align: center;">产地</span>
			      </div>
			      
			      <!-- 选项内容 - 保持与头部相同的列宽 -->
			      <el-option 
			        v-for="item in cjNameOptions" 
			        :key="item._uid" 
			        :label="item.manufacturerName" 
			        :value="item.id"
			      >
			        <div class="option-row">
			          <span style="width: 60px; flex-shrink: 0; text-align: center;">{{ item.id }}</span>
			          <span style="width: 220px; flex-shrink: 0; text-align: left; padding-left: 8px;text-overflow: ellipsis;overflow: hidden;">
			            {{ item.manufacturerName }}
			          </span>
			          <span style="width: 100px; flex-shrink: 0; text-align: center;">{{ item.coding }}</span>
			          <span style="width: 60px; text-align: center;">{{ item.origin }}</span>
			        </div>
			      </el-option>
			    </el-group>
			    
			    <!-- 加载状态提示保持不变 -->
			    <div v-if="loading" slot="empty" class="load-more">
			      <i class="el-icon-loading"></i> 加载中...
			    </div>
			    <div v-else-if="scrollLoading" slot="empty" class="load-more">
			      <i class="el-icon-loading"></i> 加载更多...
			    </div>
			    <div v-else-if="!hasMore && cjNameOptions.length > 0" slot="empty" class="load-more">
			      没有更多数据了
			    </div>
			    <div v-else-if="cjNameOptions.length === 0" slot="empty" class="load-more">
			      暂无数据
			    </div>
			  </el-select>
			</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家编码" prop="coding">
              <el-input v-model="manufacturerForm.coding"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
		<!-- 按照JS文件格式组织的其他表单项 -->
		    <el-row :gutter="20">
		      <!-- 有效天数 -->
		      <el-col :span="12">
		        <el-form-item label="有效天数" prop="expyDate">
		          <el-input v-model="manufacturerForm.expyDate"></el-input>
		        </el-form-item>
		      </el-col>
		      
		      <!-- 有效状态 -->
		      <el-col :span="12">
		        <el-form-item label="有效状态" prop="status">
		          <el-select v-model="manufacturerForm.status">
		            <el-option 
		              v-for="item in statusOptions" 
		              :key="item.id" 
		              :label="item.label" 
		              :value="item.id"
		            ></el-option>
		          </el-select>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">
		      <!-- 自付比例 -->
		      <el-col :span="12">
		        <el-form-item label="自付比例" prop="ratio">
		          <el-input v-model="manufacturerForm.ratio"></el-input>
		        </el-form-item>
		      </el-col>
		      
		      <!-- 中标次数 -->
		      <el-col :span="12">
		        <el-form-item label="中标次数" prop="bidCnt">
		          <el-input v-model="manufacturerForm.bidCnt"></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">
		      <!-- 带量采购 -->
		      <el-col :span="12">
		        <el-form-item label="带量采购" prop="cntBuy">
		          <el-select v-model="manufacturerForm.cntBuy">
		            <el-option 
		              v-for="item in YNoptions" 
		              :key="item.value" 
		              :label="item.label" 
		              :value="item.id"
		            ></el-option>
		          </el-select>
		        </el-form-item>
		      </el-col>
		      
		      <!-- 集采中选 -->
		      <el-col :span="12">
		        <el-form-item label="集采中选" prop="gatherBuyType">
		          <el-select v-model="manufacturerForm.gatherBuyType">
		            <el-option 
		              v-for="item in YNoptions" 
		              :key="item.value" 
		              :label="item.label" 
		              :value="item.id"
		            ></el-option>
		          </el-select>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">
		      <!-- 产地 -->
		      <el-col :span="12">
		        <el-form-item label="产地" prop="orplc">
		          <el-input v-model="manufacturerForm.orplc"></el-input>
		        </el-form-item>
		      </el-col>
		      
		      <!-- 批准文号 -->
		      <el-col :span="12">
		        <el-form-item label="批准文号" prop="manuLotnum">
		          <el-input v-model="manufacturerForm.manuLotnum"></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
		   <!-- 追溯字段组 -->
		   <el-row :gutter="20">
			 <!-- 小包装追溯标识码 -->
			 <el-col :span="12">
			   <el-form-item label="小包装追溯标识码" prop="drugTracMinId">
				 <el-input 
				   v-model="manufacturerForm.drugTracMinId"
				   @input="handleTraceInput('drugTracMinId')"
				   placeholder="请输入7位数字追溯码"
				 ></el-input>
			   </el-form-item>
			 </el-col>
			 
			 <!-- 大包装追溯标识码 -->
			 <el-col :span="12">
			   <el-form-item label="大包装追溯标识码" prop="drugTracMaxId">
				 <el-input 
				   v-model="manufacturerForm.drugTracMaxId"
				   @input="handleTraceInput('drugTracMaxId')"
				   placeholder="请输入7位数字追溯码"
				 ></el-input>
			   </el-form-item>
			 </el-col>
		   </el-row>
			
			<el-row :gutter="20">
			  <!-- 大包装追溯码换算数量 -->
			  <el-col :span="12">
			    <el-form-item label="追溯码换算数量(大包装)" prop="drugTracMaxCnt">
			      <el-input-number 
			        v-model="manufacturerForm.drugTracMaxCnt"
			        :min="0"
			        :step="1"
			        controls-position="right"
			      ></el-input-number>
			    </el-form-item>
			  </el-col>
			  
			  <!-- 追溯码强制扫码 -->
			  <el-col :span="12">
			    <el-form-item label="追溯码强制扫码" prop="drugTracB">
			      <el-checkbox 
			        v-model="manufacturerForm.drugTracB" 
			        :true-label="1" 
			        :false-label="0"
			      >{{ manufacturerForm.drugTracB ? '是' : '否' }}</el-checkbox>
			    </el-form-item>
			  </el-col>
			</el-row>
		    <el-row :gutter="20">
		      <!-- 网采编码 -->
		      <el-col :span="12">
		        <el-form-item label="网采编码" prop="netCode">
		          <el-input v-model="manufacturerForm.netCode"></el-input>
		        </el-form-item>
		      </el-col>
		      
		      <!-- 医保名称 -->
		      <el-col :span="12">
		        <el-form-item label="医保名称" prop="chsName">
		          <!-- 动态切换输入框和选择框 -->
		          <el-select 
		            v-if="medicalInsuranceOptions.length > 0"
		            v-model="manufacturerForm.chsName"
		            @change="handleMedicalInsuranceSelect"
		            style="width: 100%"
		          >
				  <!-- 选项组 -->
				  <el-group>
				    <!-- 固定头部 -->
				    <div class="select-header" slot="header" 
				    style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-between;padding: 8px;
				    position: sticky;top:0;z-index: 10;background-color: #f1f1f1;">
				      <span style="width: 48px;">序号</span>
				      <span>药品名称</span>
				      <span>规格</span>
				      <span>医保编码</span>
				      <span>批准文号</span>
				    </div>
				    <el-option 
				      v-for="item in medicalInsuranceOptions" 
				      :key="item.id" 
				      :label="item.label" 
				      :value="item.id"
				    >
				      <div id="optionItem">
				        <span style="width: 48px;">{{ item.id }}</span>
				        <span>{{ item.label }}</span>
				        <span>{{ item.regiSpecs }}</span>
				        <span>{{ item.mcCode }}</span>
						<el-tooltip class="item" effect="light" :content="item.specifications" placement="top">
						  <span>{{ item.approvalNumber }}</span>
						</el-tooltip>
				      </div>
				    </el-option>
				    </el-group>
		          </el-select>
		          <el-input 
		            v-else
		            v-model="manufacturerForm.chsName"
		          ></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">
		      <!-- 医保编码 -->
		      <el-col :span="12">
		        <el-form-item label="医保编码" prop="chsCode">
		          <el-input v-model="manufacturerForm.chsCode"></el-input>
		        </el-form-item>
		      </el-col>
		      
		      <!-- ypId -->
		      <el-col :span="12">
		        <el-form-item label="ypId" prop="ypId">
		          <el-input v-model="manufacturerForm.ypId"></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">
		      <!-- 注册型号 -->
		      <el-col :span="12">
		        <el-form-item label="注册型号" prop="regModel">
		          <el-input v-model="manufacturerForm.regModel"></el-input>
		        </el-form-item>
		      </el-col>
		      
		      <!-- 注册规格 -->
		      <el-col :span="12">
		        <el-form-item label="注册规格" prop="regSpc">
		          <el-input v-model="manufacturerForm.regSpc"></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
		
		    <el-row :gutter="20">

		      
		      <!-- 备注 -->
		      <el-col :span="12">
		        <el-form-item label="备注" prop="remark">
		          <el-input v-model="manufacturerForm.remark"></el-input>
		        </el-form-item>
		      </el-col>
		    </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="saveManufacturer">保存</el-button>
        <el-button size="mini" @click="manufacturerDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
  // selfs / js
  import form from './addForm.js' //Form表单
  // 从第二个JS文件中导入字段配置 基本信息
  import BasicInfo from './F2.vue';
  // 从第3个JS文件中导入字段配置 扩展信息
  import kzInfo from './F3.vue';
  // 从第4个JS文件中导入字段配置 使用注意
  import useInfo from './F4.vue';
  import { basicFieldsF2 } from './formFieldsConfigF2.js';
  // 在顶部引入pinyin-pro
  import { pinyin } from 'pinyin-pro';
  // axios
  import { getDInfo,getManufacturer } from "@/api/MedicenCata.js";
  import { addDrugInformation,updateDrugInformation,getDInfos,getPariCode } from "@/api/MedicenCata.js"; 
  import { dict } from "@/api/staff/staff.js";
export default {
  components:{
    BasicInfo,kzInfo,basicFieldsF2,useInfo
  },
  inject: ['reload'], // 无痕刷新
  data() {
    return {
	  mode: 'add', // 默认是新增模式
      dialogVisible: false,
      activeTab: 'basic',
      loading: false,
	  nameTitle:'',
      pageNum: 1, //当前页currentPage
      pageSize: 48, //每页展示条数
      totalSize: 10, //总条数
      // form: {},
      NameOptions:[],
	  cjNameOptions:[],
      drugCodeOptions: [],
      bzdwOptions:[],
      drugTypeOption:[{id:1,label:'西药'},{id:2,label:'成药'},{id:3,label:'卫材'},{id:4,label:'血液'},{id:5,label:'疫苗'}], // 药品类型
	  // 新增控制变量
	  formDisabled: false,
	  manufacturerButtonsDisabled: false,
	  disablePackingQuantity: false, // 控制包装数量是否禁用
	  showFooterButtons: true,
	  tabsDisabled: false,
      manufacturerData: [],
	  // 新增全屏状态
	  isFullscreen: false,
      addRules:{
        drugCodeId:[{ required:true,message:'此项必填',trigger:'change' }],
      },
	  statusOptions:[{id:0,label:'禁用'},{id:1,label:'可用'}], 
	  YNoptions:[{id:0,label:'否',value:'否'},{id:1,label:'是',value:'是'}],
	  rxTypeoptions:[], // 处方类型
      // 新增右键菜单相关数据
      contextMenuVisible: false,
      contextMenuX: 0,
      contextMenuY: 0,
      cascaderValue: [],
      contextMenuOptions: [
              {
                value: 'delete',
                label: '对齐方式',
                children: [
                  {
                    value: 'size-48',
                    label: '左对齐'
                  },
                  {
                    value: 'size-48',
                    label: '居中对齐'
                  },
                  {
                    value: 'size-48',
                    label: '右对齐'
                  },
                  ]
              },
              {
                value: 'batch-delete',
                label: 'Model大小',
                children: [
                  {
                    value: 'size-48',
                    label: '48%'
                  },
                  {
                    value: 'size-58',
                    label: '58%'
                  },
                  {
                    value: 'size-68',
                    label: '68%'
                  },
                  {
                    value: 'size-88',
                    label: '88%'
                  },
                  {
                    value: 'size-100',
                    label: '100%'
                  },
                  ]
              },
              {
                value: 'batch-delete',
                label: '字体大小',
                children: [
                  {
                    value: 'font-increase',
                    label: '10px (小号)'
                  },
                  {
                    value: 'font-reset',
                    label: '12px (默认)'
                  },
                  {
                    value: 'font-decrease',
                    label: '14px (常规)'
                  },
                  {
                    value: 'font-decrease',
                    label: '16px (偏大)'
                  },
                  {
                    value: 'font-decrease',
                    label: '18px (超大)'
                  },
                  {
                    value: 'font-decrease',
                    label: '20px (最大)'
                  },
                  ]
              },
              {
                value: 'settings',
                label: '排列模式',
                children: [
                  {
                    value: 'layout-2',
                    label: '每行2条'
                  },
                  {
                    value: 'layout-3',
                    label: '每行3条（默认）'
                  },
                  {
                    value: 'layout-4',
                    label: '每行4条'
                  }
                ]
              }
              ,{
                value: 'inspect',
                label: '检查网页源码',
              },
            ],
            dialogWidth: '48%',
            fontSize: 12,
            layoutMode: 3,
      // 无限滚动相关
      allSearchResults: [], // 全部搜索结果
      displayedResults: [], // 当前显示结果
	  medicalInsuranceOptions: [], // 存储医保选项
      displayBatchSize: 99, // 每批显示数量
      currentDisplayPage: 1, // 当前显示页
      scrollLoading: false, // 加载状态
      hasMore: true, // 是否有更多数据
      scrollDebounce: null, // 防抖计时器
      // 新增详情弹窗相关
      seeDetailsVisible: false,
      drugData: {},
      // 厂家相关数据
      manufacturerDialogVisible: false,
	  rsForm:{},
      manufacturerForm: {
        "expyDate":'',
        "barCode": "",
        "bidCnt": '',
        "bidLv": '',
        "chsBeginTime": "",
        "chsCode": "",
        "chsEndTime": "",
        "chsName": "",
        "clinicId": '',
        "createId": '',
        "createTime": "",
        "drugCode": "",
        "drugId": '',
		"coding":'',
        "gatherBuyType": '',
        "id": '',
        "localDrugs": '',
        "manuLotnum": "",
        "netCode": "",
        "orplc": "",
        "prodentpId": '',
        "ratio": "",
        "regBrand": "",
        "regModel": "",
        "regSpc": "",
        "remark": "",
        "spcId": "",
        "state": 1,
        "ypId": "",
		'drugTracMinId': "", // 小包装追溯标识码
		'drugTracMaxId': "", // 大包装追溯标识码
		'drugTracMaxCnt': "", // 大包装追溯码换算数量
		'drugTracB': 0, // 追溯码强制扫码
      },
	  rxColorMap: {
		'白色': '#ffffff',
		'淡红色': '#ffcccc',
		'淡黄色': '#ffffcc',
		'淡绿色': '#ccffcc',
		'淡蓝色': '#ccffff',
		'淡紫色': '#ffccff'
	  },
	  prodentrules:{
		prodentId:[{ required:true,message:'此项必填',trigger:'change' }], 
		drugTracMinId: [
		    { 
		      pattern: /^\d*$/, 
		      message: '只能输入数字', 
		      trigger: 'blur' 
		    }
		  ],
		  drugTracMaxId: [
		    { 
		      pattern: /^\d*$/, 
		      message: '只能输入数字', 
		      trigger: 'blur' 
		    }
		  ]
	  },
	  form: {
		state: 1, // 默认启用
		// 其他表单字段...
	  },
	  statusMap: {
	  	0: '禁用',
	  	1: '可用',
	  },
	  drugTracBMap: {
	  	0: '否',
	  	1: '是',
	  },
      currentManufacturer: null,
      isEditMode: false
    }
  },
  mounted() {
	this.getditc();
    this.getForm();
    // 添加滚动监听
    this.$nextTick(() => {
      const selectDropdown = document.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
      if (selectDropdown) {
        selectDropdown.addEventListener('scroll', this.handleScroll);
      }
    });
    // 初始化CSS变量
    document.documentElement.style.setProperty('--dialog-font-size', `${this.fontSize}px`)
    
    // 添加点击事件监听器，点击其他地方隐藏菜单
    document.addEventListener('click', this.hideContextMenu)
  },
  // 在beforeDestroy中移除监听
  beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener('click', this.hideContextMenu)
    const selectDropdown = document.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
    if (selectDropdown) {
      selectDropdown.removeEventListener('scroll', this.handleScroll);
    }
  },
  
  methods: {

    async open(data = {}, mode = 'view') {
      this.nameTitle = "查看药典信息"
      this.mode = mode;
      this.form = data;
      this.dialogVisible = true;
    },
    // 关闭对话框
    close() {
      this.dialogVisible = false;
    },
    // 重置表单
    reset() {
      this.form = Object.assign({}, this.$options.data.call(this).form)
    },
    // 挂载或销毁前后重新赋值后端参数
    getForm(){
      // 左侧提交表单
      this.form = form.map(v => {return v })[0]; // Form
	  this.rsForm = form.map(v => {return v })[0]; // Form
    },
	// 字典数据
	async getditc() {
	  this.result = await dict();
	  // 处理处方类型选项，添加颜色样式
	  this.rxTypeoptions = this.result.data.rxTypeVOS.map(v => {
	    const color = this.rxColorMap[v.rxColour] || '#ffffff';
	    return { 
	      label: v.name, 
	      value: v.id,
	      style: `background-color: ${color}; color: #333;`,
	      ...v 
	    };
	  });
	  console.log(this.result.data,'处方类型数据');
	},
    // 修改openAddModel方法
    openAddModel(param) {
		console.log(param,'paramparamparamparam');
      this.dialogVisible = true;
      this.nameTitle = param.label || '新增西药目录';
      this.isShow = param.isShow;
      this.system = param.system;
      this.mode = param.mode || 'add'; // 设置模式
      
      // 每次打开对话框时重置表单
      // this.resetForm();
    // 如果是编辑或查看模式，加载数据
    if ((this.mode === 'add') && param.id) {
       this.form = this.rsForm;
    }
      // 如果是编辑或查看模式，加载数据
    else  if ((this.mode === 'edit' || this.mode === 'view') && param.id) {
        this.loadEditData(param.id);
		this.drugName(); // 药典
      }
    },
	// 新增方法：加载编辑数据
	// 在methods部分修改loadEditData方法
	async loadEditData(id) {
	  try {
	    this.loading = true;
	    let res = await getDInfos({ id: id });
	    
	    if (res.code === 200) {
	      // 先重置表单
	      this.resetForm();
	      // 通知F3组件设置抗生素状态
	      if (this.$refs.kzInfo) {
	        this.$refs.kzInfo.setAntcStatus(res.data.antc === 1);
	      }
	      // 根据kcId设置包装数量禁用状态
	      this.disablePackingQuantity = res.data.kcId === 1;
	      // 通知F2组件更新包装数量禁用状态
	      if (this.$refs.basicInfo) {
	        this.$refs.basicInfo.disablePackingQuantity = this.disablePackingQuantity;
	      }
	      // 更新表单数据
	      this.form = {
	        ...this.form,
	        ...res.data
	      };
	      
	      // 确保毒麻类型选项已加载
	      await this.$refs.basicInfo.getDocVtByType();
	      
	      // 处理厂家数据
	      if (res.data.list && res.data.list.length > 0) {
	        this.manufacturerData = res.data.list;
	      } else if (res.data.manufacturerData) {
	        this.manufacturerData = res.data.manufacturerData;
	      }
	      
	      // 如果是查看模式，禁用所有表单元素
	      if (this.mode === 'view') {
	        this.formDisabled = true;
	      }
	    }
	  } finally {
	    this.loading = false;
	  }
	},
	// 禁用所有表单元素
	disableAllFormElements() {
	  // 禁用所有表单元素
	  this.formDisabled = true;
	  
	  // 禁用厂家操作按钮
	  this.manufacturerButtonsDisabled = true;
	  
	  // 修改底部按钮，只保留关闭按钮
	  this.showFooterButtons = false;
	  
	  // 禁用标签页切换（如果需要）
	  this.tabsDisabled = true;
	},
	// 更新加成率方法
	updateMarkUpRate() {
	  if (!this.form.costPric) {
	    this.$message.warning('请先填写成本单价');
	    return;
	  }
	  
	  // 调用F2组件的方法重新计算加成率
	  if (this.$refs.basicInfo) {
	    this.$refs.basicInfo.calculateMarkUpRate();
	    this.$message.success('零售单价已更新');
	  } else {
	    this.$message.error('无法更新加成率，请重试');
	  }
	},
    // 修改handleClose方法
    handleClose() {
      // 重置所有子组件表单
      this.$refs.basicInfo.resetForm();
      this.$refs.kzInfo.resetForm();
      this.$refs.useInfo.resetForm();
      
      // 重置主表单
      this.resetForm();
      this.$emit('update:visible', false);
      // 关闭对话框
      this.dialogVisible = false;
    },
    // 药典名称 =. 西药
    handlefoucsName(){
      console.log('ppppppp');
      this.drugName();
    },
	// 厂家名称 =. 
	handlefoucsNameCJ(){
      this.cjName();
    },
    // 处理复选框变化修改handleCheckboxChange方法
    handleCheckboxChange(field) {
      if (field === 'antc') {
        // 当抗生素否状态变化时，通知F3组件
        if (this.$refs.kzInfo) {
          this.$refs.kzInfo.setAntcStatus(this.form.antc === 1);
        }
      }
      this.$message.success(`${field} 值已更新为: ${this.form[field]}`);
    },
	
	// 处理复选框变化修改handleCheckboxChange方法 有效状态
	  handleCheckboxChangeState(val) {
	    this.form.state = val ? 1 : 0;
	    const message = val ? '有效状态已启用' : '有效状态已禁用';
	    this.$message({
	      message: message,
	      type: 'success'
	    });
	  },
	// 处理追溯码输入
	handleTraceInput(field) {
	  // 过滤非数字字符
	  this.manufacturerForm[field] = this.manufacturerForm[field].replace(/\D/g, '');
	  
	  // 如果输入值超过7位，截取前7位
	  if (this.manufacturerForm[field] && this.manufacturerForm[field].length > 7) {
	    this.manufacturerForm[field] = this.manufacturerForm[field].substring(0, 7);
	  }
	},
    // 修改drugName方法
    async drugName(isLoadMore = false) {
      try {
        if (!isLoadMore) {
          this.loading = true;
        } else {
          this.scrollLoading = true;
        }
        
        const res = await getDInfo({
          productName: this.currentQuery,
          pageNum: this.pageNum,
          pageSize: this.isSearchMode ? 0 : this.pageSize
        });
        
        if (res.code === 200) {
          const newData = res.data.content.map(v => ({ 
            label: v.productName, 
            ...v,
            _uid: Math.random().toString(36).substr(2, 9)
          }));
          
          if (this.isSearchMode) {
            // 搜索模式：保存所有结果
            this.allSearchResults = newData;
            
            // 显示第一批数据
            this.currentDisplayPage = 1;
            this.displayedResults = this.allSearchResults.slice(0, this.displayBatchSize);
            this.NameOptions = this.displayedResults;
            
            // 更新是否有更多数据
            this.hasMore = this.displayedResults.length < this.allSearchResults.length;
          } else {
            // 普通浏览模式
            if (isLoadMore) {
              this.NameOptions = [...this.NameOptions, ...newData];
            } else {
              this.NameOptions = newData;
            }
            this.hasMore = res.data.content.length >= this.pageSize;
          }
        }
      } catch (error) {
        console.error('获取药品数据出错:', error);
      } finally {
        this.loading = false;
        this.scrollLoading = false;
      }
    },
    // 修改searchNameMethod方法
    searchNameMethod: _.debounce(function(query) {
      this.currentQuery = query.trim();
      this.pageNum = 1;
      this.isSearchMode = true;
      
      if (!this.currentQuery) {
        this.isSearchMode = false;
        this.allSearchResults = [];
        this.drugName();
        return;
      }
      
      // 重置状态
      this.allSearchResults = [];
      this.displayedResults = [];
      this.currentDisplayPage = 1;
      this.hasMore = true;
      
      this.drugName();
    }, 500),
	
	// 厂家相关
	// 修改cjName方法
	async cjName(isLoadMore = false) {
	  try {
	    if (!isLoadMore) {
	      this.loading = true;
	    } else {
	      this.scrollLoading = true;
	    }
	    
	    const res = await getManufacturer({
			manufacturerName:this.currentQuery,
			pageNum: this.pageNum,
			pageSize: this.pageSize
	    });
	    
	    if (res.code === 200) {
	      const newData = res.data.content.map(v => ({ 
	        label: v.manufacturerName, 
	        ...v,
	        _uid: Math.random().toString(36).substr(2, 9)
	      }));
	      
	      if (this.isSearchMode) {
	        // 搜索模式：保存所有结果
	        this.allSearchResults = newData;
	        
	        // 显示第一批数据
	        this.currentDisplayPage = 1;
	        this.displayedResults = this.allSearchResults.slice(0, this.displayBatchSize);
	        this.cjNameOptions = this.displayedResults;
	        
	        // 更新是否有更多数据
	        this.hasMore = this.displayedResults.length < this.allSearchResults.length;
	      } else {
	        // 普通浏览模式
	        if (isLoadMore) {
	          this.cjNameOptions = [...this.cjNameOptions, ...newData];
	        } else {
	          this.cjNameOptions = newData;
	        }
	        this.hasMore = res.data.content.length >= this.pageSize;
	      }
	    }
	  } catch (error) {
	    console.error('获取药品数据出错:', error);
	  } finally {
	    this.loading = false;
	    this.scrollLoading = false;
	  }
	},
	CJsearchNameMethod: _.debounce(function(query) {
      this.currentQuery = query.trim();
      this.pageNum = 1;
      this.isSearchMode = true;
      
      if (!this.currentQuery) {
        this.isSearchMode = false;
        this.allSearchResults = [];
        this.cjName();
        return;
      }
      
      // 重置状态
      this.allSearchResults = [];
      this.displayedResults = [];
      this.currentDisplayPage = 1;
      this.hasMore = true;
      
      this.cjName();
    }, 500),
    // 显示右键菜单
    showContextMenu(event) {
      this.contextMenuVisible = true
      this.contextMenuX = event.clientX
      this.contextMenuY = event.clientY
      this.cascaderValue = []
      
      this.$nextTick(() => {
        this.$refs.cascaderMenu.$el.focus()
      })
    },
    // 隐藏右键菜单
    hideContextMenu() {
      this.contextMenuVisible = false
    },
    
    // 处理菜单选择
    handleMenuSelect(value) {
      if (!value || value.length === 0) return
      
      const lastValue = value[value.length - 1]
      
      switch(lastValue) {
        case 'delete':
          this.handleDelete()
          break
        case 'batch-delete':
          this.handleBatchDelete()
          break
        case 'size-48':
          this.setDialogWidth('48%')
          break
        case 'size-58':
          this.setDialogWidth('58%')
          break
        case 'size-68':
          this.setDialogWidth('68%')
          break
        case 'size-88':
          this.setDialogWidth('88%')
          break
        case 'size-100':
          this.setDialogWidth('100%')
          break
        case 'font-increase':
          this.increaseFontSize()
          break
        case 'font-decrease':
          this.decreaseFontSize()
          break
        case 'font-reset':
          this.resetFontSize()
          break
        case 'layout-2':
          this.setLayoutMode(2)
          break
        case 'layout-3':
          this.setLayoutMode(3)
          break
        // 检查网页源码
        case 'inspect':
          this.openDevTools()
          break
      }
      
      this.hideContextMenu()
    },
    // 药典选择之后快速填充
    handleNameChange(val){
      // 通过id去找到对应的对象
      let NameResult = this.NameOptions.find(name => name.id === val)
      console.log(NameResult,'去找到对应的对象');
      this.drugData = NameResult;
      if(NameResult){
        this.form.dosform = NameResult.dosageForm
        this.form.code = NameResult.drugCode
        this.form.drugCodeId = NameResult.id
        this.form.drugName = NameResult.label
        this.form.drugCodeName = NameResult.label
        this.form.drugSpec = NameResult.specifications
        this.form.drugType = 1;
        this.form.dosageForm = NameResult.dosageForm
        // 获取拼音简码（首字母第一位）
        this.form.pyCode = this.getFirstLetter(NameResult.label);

        console.log(this.form.pyCode); // 应输出 "Z"
      }
    },
	// 新增切换全屏方法
	toggleFullscreen() {
	  this.isFullscreen = !this.isFullscreen;
	},

	// 厂家选择之后快速填充
	async handleNameChangeCJ(val) {
	  // 通过id去找到对应的对象
	  let NameResult = this.cjNameOptions.find(name => name.id === val)
	  console.log(NameResult, '去找到对应的厂家对象');
	  this.drugData = NameResult;
	  if (NameResult) {
	    // 填充基础厂家信息
	    this.manufacturerForm.manufacturerName = NameResult.manufacturerName
	    this.manufacturerForm.coding = NameResult.coding
	    this.manufacturerForm.orplc = NameResult.origin
	    
	    // 新增：调用医保信息接口
	    await this.getMedicalInsuranceInfo(
	      this.form.drugName, // 外层药品名称
	      '', // 医保编码初始为空
	      this.manufacturerForm.manuLotnum || '', // 厂家表单中的批准文号
	      NameResult.manufacturerName // 已选择的厂家名称
	    );
	  }
	},
	
	// 获取医保信息
	async getMedicalInsuranceInfo(drugName, chsCode , approvalNumber, manufacturerName) {
	  try {
	    this.loading = true;
	    const res = await getPariCode({ 
	      drugName: drugName,
	      chsCode: chsCode,
	      approvalNumber: approvalNumber,
	      prodentpName: manufacturerName
	    });
	    
	    if (res.code === 200 && res.data) {
	      console.log('医保信息结构:', res.data);
	      
	      // 存储医保选项
	      this.medicalInsuranceOptions = res.data.map(item => ({
			id: item.id,
	        label: item.registeredName,
	        ...item
	      }));
	      
	      // 自动填充医保名称和编码（如果有数据）
	      if (this.medicalInsuranceOptions.length > 0) {
	        this.manufacturerForm.chsName = this.medicalInsuranceOptions[0].label;
	        this.manufacturerForm.chsCode = this.medicalInsuranceOptions[0].value;
	      }
	      
	      this.$message.success('医保信息已自动填充');
	    } else {
	      console.warn('未获取到医保信息');
	      this.$message.info('未找到匹配的医保信息');
	    }
	  } catch (error) {
	    console.error('获取医保信息失败:', error);
	    this.$message.error('获取医保信息失败');
	  } finally {
	    this.loading = false;
	  }
	},
	
    // 打开开发者工具
    openDevTools() {
      try {
        // 尝试使用浏览器API打开开发者工具
        if (window.chrome && chrome.devtools) {
          chrome.devtools.inspectedWindow.eval('console.log("开发者工具已打开")')
        } else {
          // 模拟F12按键
          const event = new KeyboardEvent('keydown', {
            key: 'F12',
            code: 'F12',
            keyCode: 123,
            which: 123,
            bubbles: true,
            cancelable: true
          })
          document.dispatchEvent(event)
        }
        this.$message.success('已尝试打开开发者工具')
      } catch (e) {
        this.$message.warning('无法直接打开开发者工具，请手动按F12')
      }
    },
    // 复制药品名称
    copyDrugName() {
      // 检查是否已选择药品
      if (!this.form.drugName) {
        this.$message.warning('请先选择药典信息');
        return;
      }
      
      // 创建临时textarea元素
      const textarea = document.createElement('textarea');
      textarea.value = this.form.drugName;
      textarea.style.position = 'fixed';  // 防止页面滚动
      document.body.appendChild(textarea);
      textarea.select();
      
      try {
        // 执行复制命令
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('药品名称已复制到剪贴板');
        } else {
          this.$message.error('复制失败，请手动复制');
        }
      } catch (err) {
        this.$message.error('复制失败: ' + err);
      }
      
      // 移除临时元素
      document.body.removeChild(textarea);
    },
    
    // Others
    // 新增方法：获取字符串的首字母
    getFirstLetter(str) {
      if (!str || typeof str !== 'string') return '';
      
      try {
        // 1. 用正则提取所有汉字（过滤非汉字字符）
        const chineseChars = str.match(/[\u4e00-\u9fa5]/g) || [];
        if (chineseChars.length === 0) return '';
    
        // 2. 对每个汉字获取拼音首字母
        const initials = chineseChars.map(char => {
          const pinyinResult = pinyin(char, {
            toneType: 'none',
            type: 'array',
            multiple: false, // 只取第一个读音
          })[0] || '';
          return pinyinResult.charAt(0).toUpperCase();
        });
    
        // 3. 组合成简码（如"中国" → "ZG"）
        return initials.join('');
      } catch (error) {
        console.error('拼音转换失败:', error);
        return '';
      }
    },
    // 添加滚动处理方法
    handleScroll(event) {
      const { scrollTop, scrollHeight, clientHeight } = event.target;
      const threshold = 50; // 距离底部50px时加载
      
      if (scrollHeight - (scrollTop + clientHeight) < threshold && this.hasMore && !this.scrollLoading) {
        this.loadMoreData();
      }
    },
    handleFormUpdate(updatedData) {
      // 合并子组件更新的数据到表单
      this.form = {
        ...this.form,
        ...updatedData
      };
    },
    handleFormUpdateF3(updatedData) {
      // 合并子组件更新的数据到表单
      this.form = {
        ...this.form,
        ...updatedData
      };
    },
    handleFormUpdateF4(updatedData) {
      // 合并子组件更新的数据到表单
      this.form = {
        ...this.form,
        ...updatedData
      };
    },
    // 加载更多数据方法
    async loadMoreData() {
      if (this.isSearchMode) {
        // 搜索模式下的分页加载
        this.currentDisplayPage++;
        const start = (this.currentDisplayPage - 1) * this.displayBatchSize;
        const end = start + this.displayBatchSize;
        this.displayedResults = this.allSearchResults.slice(0, end);
        this.NameOptions = this.displayedResults;
        this.hasMore = end < this.allSearchResults.length;
      } else {
        // 普通浏览模式的分页加载
        this.pageNum++;
        await this.drugName(true);
      }
    },
    showDetails() {
      if (!this.form.drugCodeName) {
        this.$message.warning('请先选择药典数据');
        return;
      }
      this.seeDetailsVisible = true;
    },
    // 关闭详情弹窗
    handleCloseDetails(done) {
      done();
    },
    
    // 厂家相关方法
    handleManufacturerSelect(currentRow) {
      this.currentManufacturer = currentRow;
    },
    
	// 处理医保名称选择
	handleMedicalInsuranceSelect(selectedLabel) {
		console.log(selectedLabel,'lllllllllll')
	  // 根据选中的医保名称，在medicalInsuranceOptions中找到对应的选项
	  const selectedOption = this.medicalInsuranceOptions.find(option => option.id == selectedLabel);
	  if (selectedOption) {
	    // 将选中的医保编码赋值到chsCode
	    this.manufacturerForm.chsCode = selectedOption.mcCode;
	  }
	},
	
	// 添加厂家
	addManufacturer() {
	  this.isEditMode = false;
	  this.currentManufacturer = null;
	  this.manufacturerForm = {
	    "expyDate":'',
	    "barCode": "",
	    "bidCnt": '',
	    "bidLv": '',
	    "chsBeginTime": "",
	    "chsCode": "",
	    "chsEndTime": "",
	    "chsName": "",
	    "clinicId": '',
	    "createId": '',
	    "createTime": "",
	    "drugCode": "",
	    "drugId": '',
	    "coding":'',
	    "gatherBuyType": '',
	    "id": '',
	    "localDrugs": '',
	    "manuLotnum": "",
	    "netCode": "",
	    "orplc": "",
	    "prodentpId": '',
	    "ratio": "",
	    "regBrand": "",
	    "regModel": "",
	    "regSpc": "",
	    "remark": "",
	    "spcId": "",
	    "status": 1,
	    "ypId": "",
		'drugTracMinId': "", // 小包装追溯标识码
		'drugTracMaxId': "", // 大包装追溯标识码
		'drugTracMaxCnt': "", // 大包装追溯码换算数量
		'drugTracB': 0, // 追溯码强制扫码
	  };
	  this.manufacturerDialogVisible = true;
	},
    
    // 编辑厂家
    editManufacturer() {
      if (!this.currentManufacturer) {
        this.$message.warning('请先选择一条厂家记录');
        return;
      }
      
      this.isEditMode = true;
      // 深拷贝当前行数据
      this.manufacturerForm = JSON.parse(JSON.stringify(this.currentManufacturer));
      
      // 特殊处理：如果编辑模式下有医保信息，设置医保选项
      if (this.manufacturerForm.chsName && this.manufacturerForm.chsCode) {
        this.medicalInsuranceOptions = [{
          label: this.manufacturerForm.chsName,
          value: this.manufacturerForm.chsCode
        }];
      } else {
        this.medicalInsuranceOptions = [];
      }
      
      this.manufacturerDialogVisible = true;
    },
    
    deleteManufacturer() {
      if (!this.currentManufacturer) {
        this.$message.warning('请先选择一条厂家数据');
        return;
      }
      
      this.$confirm('确认删除该厂家信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.manufacturerData.indexOf(this.currentManufacturer);
        if (index !== -1) {
          this.manufacturerData.splice(index, 1);
          this.$message.success('厂家信息已删除');
          this.currentManufacturer = null;
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
	// 保存厂家信息
	saveManufacturer() {
     this.$refs.manufacturerForm.validate(valid => {
       if (valid) {
         if (this.isEditMode && this.currentManufacturer) {
           // 编辑模式 - 更新现有记录
           const index = this.manufacturerData.findIndex(
             item => item.id === this.currentManufacturer.id
           );
           if (index !== -1) {
             // 使用$set确保响应式更新
             this.$set(this.manufacturerData, index, {
               ...this.manufacturerForm
             });
             this.$message.success('厂家信息更新成功');
           }
         } else {
           // 新增模式 - 添加新记录
           const newManufacturer = {
             ...this.manufacturerForm,
             id: Date.now() // 生成唯一ID
           };
           
           // 检查是否是第一条默认数据（示例数据）
           if (this.manufacturerData.length === 1 && 
               this.manufacturerData[0].manufacturerName === '示例宜宾制药厂') {
             // 替换默认数据
             this.manufacturerData.splice(0, 1, newManufacturer);
             this.$message.success('厂家信息添加成功');
           } else {
             // 正常添加新数据
             this.manufacturerData.push(newManufacturer);
             this.$message.success('厂家信息添加成功');
           }
         }
         this.manufacturerDialogVisible = false;
       }
     });
   },
    
    handleCloseManufacturerDialog(done) {
      this.$confirm('确认关闭厂家信息窗口?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
        this.currentManufacturer = null;
      }).catch(() => {
        this.$message.info('已取消关闭');
      });
    },
    // 修改submitForm方法
    submitForm() {
      // 首先校验主表单
      this.$refs.topForm.validate(valid => {
        if (!valid) {
          this.$message.error('请填写完整表单信息');
          return false;
        }
        
        // 检查厂家信息是否存在
        if (this.manufacturerData.length === 0 || 
            (this.manufacturerData.length === 1 && 
             this.manufacturerData[0].manufacturerName === '示例宜宾制药厂')) {
          this.$confirm('检测到您当前还未填写厂家信息, 是否前往填写?', '提示:厂家信息为必填项。', {
            confirmButtonText: '去填写',
            cancelButtonText: '关闭提示',
            type: 'warning'
          }).then(() => {
            this.manufacturerDialogVisible = true;
          }).catch(() => {
            this.$message({ type: 'error', message: '厂家信息为必填项！'});
          });
          return;
        }
        
        // 校验所有子组件表单
        this.validateChildForms().then(allValid => {
          if (allValid) {
            if (this.mode === 'add') {
              this.handleSubmitData();
            } else {
              this.editForm();
            }
          } else {
            // this.$message.error('请检查表单中的错误');
          }
        });
      });
    },

	// 新增方法：校验所有子组件表单
	validateChildForms() {
	  return new Promise(resolve => {
	    try {
	      const promises = [];
	      const invalidTabs = [];
	      
	      // 校验基本信息标签页
	      if (this.$refs.basicInfo && this.$refs.basicInfo.$refs.form) {
	        promises.push(new Promise(resolve => {
	          this.$refs.basicInfo.$refs.form.validate(valid => {
	            if (!valid) {
	              invalidTabs.push('basic');
	              console.error('基本信息标签页验证失败');
	            }
	            resolve(valid);
	          });
	        }));
	      } else {
	        console.error('basicInfo ref 或 form ref 未找到');
	      }
	      
	      // 校验扩展信息标签页
	      if (this.$refs.kzInfo && this.$refs.kzInfo.$refs.form) {
	        promises.push(new Promise(resolve => {
	          this.$refs.kzInfo.$refs.form.validate(valid => {
	            if (!valid) {
	              invalidTabs.push('extended');
	              console.error('扩展信息标签页验证失败');
	            }
	            resolve(valid);
	          });
	        }));
	      } else {
	        console.error('kzInfo ref 或 form ref 未找到');
	      }
	      
	      // 校验使用注意标签页
	      if (this.$refs.useInfo && this.$refs.useInfo.$refs.form) {
	        promises.push(new Promise(resolve => {
	          this.$refs.useInfo.$refs.form.validate(valid => {
	            if (!valid) {
	              invalidTabs.push('usage');
	              console.error('使用注意标签页验证失败');
	            }
	            resolve(valid);
	          });
	        }));
	      } else {
	        console.error('useInfo ref 或 form ref 未找到');
	      }
	      
	      // 等待所有子组件校验完成
	      Promise.all(promises).then(results => {
	        if (invalidTabs.length > 0) {
	          // 切换到第一个有错误的标签页
	          this.activeTab = invalidTabs[0];
	          this.$message.error(`请检查${this.getTabName(invalidTabs[0])}标签页中的错误`);
	        }
	        resolve(results.every(valid => valid));
	      });
	    } catch (error) {
	      console.error('表单验证出错:', error);
	      resolve(false);
	    }
	  });
	},
	
	getTabName(tab) {
	  const tabNames = {
	    basic: '基本信息',
	    extended: '扩展信息',
	    usage: '使用注意'
	  };
	  return tabNames[tab] || tab;
	},
	// submitForm() {
	//   // 首先进行表单验证
	//   this.$refs.topForm.validate(valid => {
	//     if (!valid) {
	//       this.$message.error('请填写完整表单信息');
	//       return false;
	//     }
	    
	//     // 检查厂家信息是否存在
	//     if (this.manufacturerData.length === 0 || 
	//         (this.manufacturerData.length === 1 && 
	//          this.manufacturerData[0].manufacturerName === '示例宜宾制药厂')) {
	//       this.$confirm('检测到您当前还未填写厂家信息, 是否前往填写?', '提示:厂家信息为必填项。', {
	//         confirmButtonText: '去填写',
	//         cancelButtonText: '关闭提示',
	//         type: 'warning'
	//       }).then(() => {
	//         // 聚焦到厂家信息区域
	//         this.manufacturerDialogVisible = true;
	//       }).catch(() => {
	//         this.$message({ type: 'error', message: '厂家信息为必填项！'});
	//       });
	//       return;
	//     }
	    
	//     // 所有验证通过，提交数据
	//     this.handleSubmitData();
	//   });
	// },
	// 新增handleEditSubmit方法
	async handleEditSubmit() {
		console.log(this.form,'pppppppppppppppppppppppppp');
	  try {
	    // 准备提交数据
	    const submitData = {
	      ...this.form,
	      list: this.manufacturerData.filter(item => item.manufacturerName && item.manufacturerName !== '示例宜宾制药厂')
	    };
	    
	    // 调用修改API
	    let res = await updateDrugInformation(submitData);
	    
	    if (res.code === 200) {
	      this.$message.success('修改药品信息成功');
	      
	      // 关闭对话框
	      this.dialogVisible = false;
	      
	      // 通知父组件刷新数据
	      this.$emit('refresh');
	    } else {
	      this.$message.error(res.message || '修改药品信息失败');
	    }
	  } catch (error) {
	    console.error('提交药品信息出错:', error);
	    this.$message.error('提交药品信息出错');
	  }
	},
	// 修改editForm方法
	async editForm() {
		
	  // 首先进行表单验证
	  this.$refs.topForm.validate(valid => {
	    if (!valid) {
	      this.$message.error('请填写完整表单信息');
	      return false;
	    }
	    
	    // 检查厂家信息
	    if (this.manufacturerData.length === 0 || 
	        (this.manufacturerData.length === 1 && 
	         this.manufacturerData[0].manufacturerName === '示例宜宾制药厂')) {
	      this.$confirm('检测到您当前还未填写厂家信息, 是否前往填写?', '提示:厂家信息为必填项。', {
	        confirmButtonText: '去填写',
	        cancelButtonText: '关闭提示',
	        type: 'warning'
	      }).then(() => {
	        this.manufacturerDialogVisible = true;
	      }).catch(() => {
	        this.$message({ type: 'error', message: '厂家信息为必填项！'});
	      });
	      return;
	    }
	    // 所有验证通过，提交数据
	    this.handleEditSubmit();
	  });
	},
	// 提交数据的实际方法
	async handleSubmitData() {
	  try {
	    // 准备提交数据
	    const submitData = {
	      ...this.form,
	      list: this.manufacturerData.filter(item => item.manufacturerName && item.manufacturerName !== '示例宜宾制药厂')
	    };
	    
	    // 调用API
	    let res;
	    if (this.mode === 'add') {
	      res = await addDrugInformation(submitData);
	    } else {
	      res = await updateDrugInformation(submitData);
	    }
	    if (res.code === 200) {
	          // 直接刷新整个页面
			  location.reload();
			  setTimeout(()=>{
				  this.$message.success(this.mode === 'add' ? '新增药品信息成功' : '修改药品信息成功');
				  // 重置所有表单
				  this.$refs.basicInfo.resetForm();
				  this.$refs.kzInfo.resetForm();
				  this.$refs.useInfo.resetForm();
				  this.resetForm();
				  
				  // 关闭对话框
				  this.dialogVisible = false;
				  
				  // 通知父组件刷新数据
				  this.$emit('refresh');
			  },1200)
	          
	        }
	      }  catch (error) {
	    console.error('提交药品信息出错:', error);
	    this.$message.error('提交药品信息出错');
	  }
	},
	
	// 新增方法：重置所有子组件表单
	resetChildForms() {
	  if (this.$refs.basicInfo && this.$refs.basicInfo.resetForm) {
	    this.$refs.basicInfo.resetForm();
	  }
	  if (this.$refs.kzInfo && this.$refs.kzInfo.resetForm) {
	    this.$refs.kzInfo.resetForm();
	  }
	  if (this.$refs.useInfo && this.$refs.useInfo.resetForm) {
	    this.$refs.useInfo.resetForm();
	  }
	  
	  // 重置主表单
	  this.resetForm();
	},
	
	// 重置表单方法
	// 在methods部分修改resetForm方法
	resetForm() {
	  // 深拷贝初始表单数据
	  this.form = JSON.parse(JSON.stringify(form[0]));
	  this.form.drugType = 1; // 设置默认药品类型
	  
	  // 重置厂家数据
	  this.manufacturerData = [{
	    manufacturerName: '示例宜宾制药厂',
	    coding: 'YB123',
	    insuranceType: '甲类',
	    origin: '宜宾',
	    registrant: '示例公司',
	    approvalNumber: '国药准字Z123456',
	    factory: '宜宾分厂',
	    selfPayRatio: '10%'
	  }];
	  
	  // 重置其他状态
	  this.currentManufacturer = null;
	  this.isEditMode = false;
	  this.formDisabled = false;
	  this.activeTab = 'basic';
	  
	  // 重置表单验证
	  if (this.$refs.topForm) {
	    this.$refs.topForm.clearValidate();
	  }
	},

  }
}
</script>

<style lang="less" scoped>
	/* 添加或修改以下样式 */
	/* 在style部分添加 */
	.manufacturer-dialog {
	  .el-dialog {
	    border-radius: 8px;
	    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	  }
	  
	  .el-dialog__header {
	    background: linear-gradient(to right, #1a6be0, #409EFF);
	    border-radius: 8px 8px 0 0;
	    padding: 12px 20px;
	    
	    .el-dialog__title {
	      color: white;
	      font-weight: bold;
	      font-size: 16px;
	    }
	  }
	  
	  .el-dialog__body {
	    padding: 20px;
	    max-height: 70vh;
	    overflow-y: auto;
	    
	    .el-form {
	      .el-form-item {
	        margin-bottom: 16px;
	        
	        .el-form-item__label {
	          font-weight: 600;
	          color: #333;
	          padding-right: 10px;
	        }
	        
	        .el-input, .el-select, .el-input-number {
	          width: 100%;
	        }
	      }
	      
	      .el-row {
	        margin-bottom: 8px;
	      }
	    }
	  }
	  
	  .el-dialog__footer {
	    padding: 15px 20px;
	    border-top: 1px solid #eee;
	    text-align: center;
	    
	    .el-button {
	      min-width: 90px;
	      border-radius: 4px;
	    }
	  }
	  
	  /* 新增字段样式 */
	  .traceability-fields {
	    background-color: #f9f9f9;
	    padding: 15px;
	    border-radius: 6px;
	    margin-top: 15px;
	    border: 1px solid #eaeaea;
	    
	    .el-form-item {
	      margin-bottom: 12px;
	    }
	  }
	}
	.select-header {
	  box-sizing: border-box;
	}
	
	.option-row {
	  display: flex;
	  align-items: center;
	  width: 100%;
	  font-size: 12px;
	  border: 1px solid #00557f;
	  span{
		  border-right: 1px solid #00557f;
	  }
	}
	
	.el-select-dropdown__item {
	  padding: 0 !important;
	  height: auto !important;
	}
	
	.el-select-dropdown__item.selected {
	  background-color: #f5f7fa;
	}
	
	.el-select-dropdown__item.hover {
	  background-color: #f5f7fa;
	}
	
	.load-more {
	  text-align: center;
	  padding: 8px;
	  color: #909399;
	  font-size: 12px;
	}
	.dialog-header {
	  display: flex;
	  height: 28px;
	  justify-content: space-between;
	  align-items: center;
	  width: 100%;
	  span{
		  color: #fff;
		  font-size: 12px;
	  }
	  .header-buttons {
	    display: flex;
	    align-items: center;
	    
	    /deep/ .el-button {
	      padding: 0;
	      margin-left: 8px;
	      color: #fff;
	      
	      &:hover {
	        color: #409EFF;
	        background-color: transparent;
	      }
	    }
	  }
	}
	
	/* 调整全屏模式下的样式 */
	.drug-info-dialog {
	  /deep/ &.is-fullscreen {
	    .el-dialog {
	      width: 100% !important;
	      height: 100%;
	      margin: 0 !important;
	      max-height: none;
	    }
	    
	    .el-dialog__body {
	      height: calc(100% - 55px);
	      overflow: auto;
	    }
	  }
	}
.drug-info-dialog {
  font-family: "Microsoft YaHei", sans-serif;
}
/* 自定义Cascader面板样式 */
.el-cascader-panel {
  font-size: 12px;
  background-color: #d6d6d6;
  .el-cascader-menu {
    min-width: 50px;
    .el-cascader-node {
      padding: 8px 16px;
      height: auto;
      line-height: 1.5;
      
      &:hover {
        background-color: #6f6f6f;
      }
      
      &.is-active {
        color: #fff;
        font-weight: bold;
      }
    }
  }
}
.form-top {
  padding: 0px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 4px;

  /deep/ .el-tabs--border-card{
    width: 100%;
  }
  /deep/ .el-input--mini .el-input__inner{
    height: 26px;
  }
  /deep/ .el-form-item__content{
    // margin-left: -8px;
  }
  /deep/ .el-form-item__label{
    font-size: 12px;
    width: 100px;
  }
  .select-header{
    span{
      width: 168px;
      text-align: center;
    }
  }
  #optionItem {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    text-align: left;
    justify-content: space-between;border: 1px solid #a3a3a3;
    span{
      padding-left: 8px;
      border-right: 1px solid #a3a3a3;
      display: inline-block;
      width: 168px;
      font-size: 12px;
      // height: 26px;
      // line-height: 26px;
      white-space: nowrap;      /* 禁止换行 */
      overflow: hidden;         /* 隐藏溢出内容 */
      text-overflow: ellipsis;  /* 溢出显示省略号 */
    }
  }
}

/* 在style部分添加 */
.manufacturer-dialog {
  .el-dialog {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  .el-dialog__header {
    background: linear-gradient(to right, #1a6be0, #409EFF);
    border-radius: 8px 8px 0 0;
    padding: 12px 20px;
    
    
  }
  
  .el-dialog__body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
    
    .el-form {
      .el-form-item {
        margin-bottom: 16px;
        
        .el-form-item__label {
          font-weight: 600;
          color: #333;
          padding-right: 10px;
        }
        
        .el-input, .el-select, .el-input-number {
          width: 100%;
        }
      }
      
      .el-row {
        margin-bottom: 8px;
      }
    }
  }
  
  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #eee;
    text-align: center;
    
    .el-button {
      min-width: 90px;
      border-radius: 4px;
    }
  }
  
  /* 新增字段样式 */
  .traceability-fields {
    background-color: #f9f9f9;
    padding: 15px;
    border-radius: 6px;
    margin-top: 15px;
    border: 1px solid #eaeaea;
    
    .el-form-item {
      margin-bottom: 12px;
    }
  }
}
.form-main {
  margin-bottom: 4px;
}

.tab-content {
  // padding: 15px;
  // min-height: 200px;
}

.form-feet {
  /* margin-top: 1px; */
}

.CJ {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  overflow: hidden;
}

.CJ-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background: #00557f;
  color: white;
  font-size: 14px;
}

.title-text {
  font-weight: bold;
  font-size: 12px;
}

.title-buttons .el-button {
  padding: 0px;
  color: white;
}

.CJ-table {
  width: 100%;
}

.el-table {
  width: 100%;
}

.el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: auto;
}

.el-table--scrollable-y .el-table__body-wrapper {
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
  padding: 10px 10px 0;
  border-top: 1px solid #e6e6e6;
  font-size: 12px;
  .el-button{
  
  }
}

/* 调整表单行间距 */
.el-form-item {
  margin-bottom: 4px;
}
#optionItem {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    text-align: left;
    justify-content: space-between;border: 1px solid #a3a3a3;
    span{
      padding-left: 18px;
      border-right: 1px solid #a3a3a3;
      display: inline-block;
      width: 88px;
      font-size: 12px;
      // height: 26px;
      // line-height: 26px;
      white-space: nowrap;      /* 禁止换行 */
      overflow: hidden;         /* 隐藏溢出内容 */
      text-overflow: ellipsis;  /* 溢出显示省略号 */
    }
  }
</style>